package com.quikin.persistence.stdjpa.service.aa;

import java.sql.Timestamp;

import org.apache.log4j.Logger;

import com.quikin.persistence.jpa.entity.aa.AuthenticationInfo;
import com.quikin.persistence.jpa.entity.aa.UserProfile;
import com.quikin.persistence.jpa.util.QuikinPLErrorCode;
import com.quikin.persistence.jpa.util.QuikinPLException;
import com.quikin.persistence.stdjpa.controller.aa.AuthenticationInfoController;

public class AAEntryService {
    
    private static final Logger logger = Logger.getLogger(AAEntryService.class);

    private static AAEntryService instance;
    
    private AAEntryService() {
        
    }
    
    public static AAEntryService getInstance() {
        if (instance == null) {
            instance = new AAEntryService();
        }
        return instance;
    }
    
    public UserProfile login(String loginId, String password) {
        AuthenticationInfoController aiCtrl = AuthenticationInfoController.getInstance();
        AuthenticationInfo info = aiCtrl.getByLoginId(loginId);
        if (info == null) {
            throw new QuikinPLException(QuikinPLErrorCode.USER_LOGINID_NOT_EXIST);
        }
        if (!info.getPassword().equals(password)) {
            info.setPwdErrCnt(info.getPwdErrCnt().intValue() + 1);
            throw new QuikinPLException(QuikinPLErrorCode.USER_PASSWORD_INCORRECT);
        }
        UserProfile user = info.getUserProfile();
        if (user == null) {
            throw new QuikinPLException(QuikinPLErrorCode.USER_NOT_EXIST);
        }
        info.setPwdErrCnt(0);
        info.setLastLoginTime(new Timestamp(System.currentTimeMillis()));
        return user;
    }
}
